package com.glacier.common.support.utils;

import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * date 2023-01-20 21:29
 * spring bean 上下文工具类
 *
 * @author glacier
 * @version 1.0.0
 */
@Component
public class SpringContextHolder implements ApplicationContextAware {
    /**
     * 上下文对象实例
     */
    private static ApplicationContext context;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) {
        SpringContextHolder.context = applicationContext;
    }

    /**
     * 获取上下文
     *
     * @return
     */
    public static ApplicationContext getContext() {
        return context;
    }

    /**
     * 根据名称获取实例
     *
     * @param name
     * @param <T>
     * @return
     */
    @SuppressWarnings("unchecked")
    public static <T> T getBean(String name) {
        return (T) context.getBean(name);
    }

    /**
     * 根据类型获取实例
     *
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T getBean(Class<T> clazz) {
        return context.getBean(clazz);
    }
}
